clear all;clc
addpath(genpath('.'));  %添加工具箱路径
% load r %嵌入半径
%% 开始计时
tic 

xyloObj = VideoReader('./Video_data/5_1080.mp4');
% frame = read(xyloObj,67); % first frame only 获取第一帧
Frame_num=xyloObj.NumFrames;
fps = xyloObj.FrameRate;
out = VideoWriter('./Video_stego/5_marked');%默认avi封装格式
out.FrameRate = fps;
open(out);
rep_time=fix(Frame_num/(64*5));%5代表每5帧1bit，64表示一个周期嵌64bit
%% 秘密信息生成
load key; rng(key);%%key为伪随机序列种子
msg = num2str(uint8(rand(1,64)));
msg=strrep(msg,' ','');%剔除空格
msg=repmat(msg,1,rep_time);
L=length(msg);
p=1;%指向msg的指针

%% cross-embed
% 连续5帧1bit，抵抗时域去同步攻击
% DFT域水印信号，左0，右1
% 嵌完一个组之后，空5~10帧不嵌，代表一个组的分离
PSNR=[];
SSIM=[];
tt=1;
for f=1:5:Frame_num
    if p>L
        break;
    end
    [emb_msg,p]=get_msg(msg,p,1);%取1bit
    for c=1:5
        if tt==Frame_num
            break;
        end
        ycbcrframe = rgb2ycbcr(readFrame(xyloObj));%imshow(frame);%一次一帧
        Y_Cover=ycbcrframe(:,:,1);
        if strcmp(emb_msg,'1')  %嵌入DFT水印，代表水印1
            Stego_Y=dft_emd_1(Y_Cover,35,33);%1-3象限    
        else
            Stego_Y=dft_emd_2(Y_Cover,35,33);%2-4象限
        end
        ps=find_psnr(Stego_Y,Y_Cover);
        ss=find_ssim(Stego_Y,Y_Cover);
%         disp(['dft:',num2str(ps)]);
        PSNR=[PSNR;ps];
        SSIM=[SSIM;ss];
        Stego=cat(3,Stego_Y,ycbcrframe(:,:,2),ycbcrframe(:,:,3));
        Stego=ycbcr2rgb(Stego);
        writeVideo(out, Stego);
        tt=tt+1;
    end
    if mod(p,64)==0 %嵌入DCT同步信号
        cc=5;%5帧DCT同步
        while(cc)
            Cover=readFrame(xyloObj);
            SS=Cover;
            block_size=8;
            [row,col]=size(Cover(:,:,1));w=fix(row/block_size);h=fix(col/block_size);
            emd_zoom=imcrop(Cover,[1 1 h*block_size-1 w*block_size-1]);
            XX=rgb2ycbcr(emd_zoom);XXX=double(XX(:,:,1));
            Stego_Y=blockproc(XXX,[block_size block_size],@DCT_synchronization);
            S=cat(3,Stego_Y,XX(:,:,2),XX(:,:,3));
            Stego=ycbcr2rgb(S);
            ps=find_psnr(Stego_Y,XXX);
            ss=find_ssim(Stego_Y,XXX);
            PSNR=[PSNR;ps];
            SSIM=[SSIM;ss];
            SS(1:w*block_size,1:h*block_size,:)=Stego;
            writeVideo(out,SS);
            cc=cc-1;
            tt=tt+1;
            disp(['DCT同步',num2str(cc),'帧']);
        end
    end
    disp(['已完成',num2str(100*tt/Frame_num),'%']);
end
close(out);
mytimer1=toc;
disp(['程序运行时间',num2str(mytimer1),'平均每帧运行时间',num2str(mytimer1/Frame_num)])
disp(['平均PSNR',num2str(mean(PSNR)),'平均SSIM',num2str(mean(SSIM))])